package com.ruoyi.web.controller.system;

import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.com.service.IComMenuService;
import com.ruoyi.com.service.IComUserService;
import com.ruoyi.common.core.domain.entity.*;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.service.ISysDepartmentRoleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.service.SysPermissionService;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.domain.SysUserRole;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysRoleService;
import com.ruoyi.system.service.ISysUserService;

/**
 * 角色信息
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/system/role")
@Api(value = "子系统角色信息", tags = {"子系统角色信息"})
public class SysRoleController extends BaseController
{
    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private IComMenuService comMenuService;


    @Autowired
    private ISysDepartmentRoleService sysDepartmentRoleService;

    /**
     * 查询子系统所有角色
     */
    @GetMapping("/allList")
    @ApiOperation(value = "查询统一门户所有角色")
    public AjaxResult allList(SysRole role)
    {
        Long deptId = SecurityUtils.getLoginUser().getDeptId();
        role.setDeptId(deptId);
        List<SysRole> list = roleService.selectRoleList(role);
        return success(list);
    }

    @GetMapping("/list")
    @ApiOperation(value = "获取角色列表")
    public TableDataInfo list(SysRole role)
    {
        startPage();
        Long deptId = SecurityUtils.getLoginUser().getDeptId();
        role.setDeptId(deptId);
        List<SysRole> list = roleService.selectRoleList(role);
        return getDataTable(list);
    }


    /**
     * 根据角色编号获取详细信息
     */
    @GetMapping(value = "/{roleId}")
    @ApiOperation(value = "获取角色详情")
    public AjaxResult getInfo(@PathVariable Long roleId)
    {
        return success(roleService.selectRoleById(roleId));
    }

    /**
     * 新增角色
     */
    @Log(title = "角色管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysRole role)
    {
        if (!roleService.checkRoleNameUnique(role))
        {
            return error("新增角色'" + role.getRoleName() + "'失败，角色名称已存在");
        }
        Long deptId = SecurityUtils.getLoginUser().getDeptId();
        role.setStatus("0");
        role.setDeptId(deptId);
        role.setCreateBy(getUsername());
        role.setUpdateId(getUserId());
        return toAjax(roleService.insertRole(role));

    }

    /**
     * 修改保存角色
     */
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysRole role)
    {
        if (!roleService.checkRoleNameUnique(role))
        {
            return error("修改角色'" + role.getRoleName() + "'失败，角色名称已存在");
        }
        role.setUpdateBy(getUsername());
        role.setUpdateId(getUserId());
        return toAjax(roleService.updateRole(role));
    }


//    /**
//     * 状态修改
//     */
//    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
//    @PutMapping("/changeStatus")
//    public AjaxResult changeStatus(@RequestBody SysRole role)
//    {
//        roleService.checkRoleAllowed(role);
//        roleService.checkRoleDataScope(role.getRoleId());
//        role.setUpdateBy(getUsername());
//        return toAjax(roleService.updateRoleStatus(role));
//    }

    /**
     * 删除角色
     */
    @Log(title = "角色管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{roleId}")
    public AjaxResult remove(@PathVariable Long roleId)
    {
        //查看角色是否被用户占用
        Integer count = roleService.selectUserRoleByRoleId(roleId);
        if(count > 0){
            return warn("该角色已被绑定，无法删除");
        }
        //查看角色是否被岗位占用
        Integer countTwo = sysDepartmentRoleService.selectDepartmentByRoleId(roleId);
        if(countTwo > 0){
            return warn("该角色已被绑定，无法删除");
        }
        return toAjax(roleService.deleteRoleByIds(roleId));
    }

    /**
     * 分配菜单权限
     */
    @PostMapping(value = "/insertRoleMenu")
    @ApiOperation(value = "分配菜单权限")
    public AjaxResult insertRoleMenu(@RequestBody SysRole role)
    {
        return toAjax(roleService.insertRoleMenu(role));
    }


    /**
     * 加载对应角色菜单列表树
     */
    @GetMapping(value = "/roleMenuTreeselect/{roleId}")
    @ApiOperation(value = "加载对应角色菜单列表树")
    public AjaxResult roleMenuTreeselect(@PathVariable("roleId") Long roleId)
    {
        List<ComMenu> menus = comMenuService.selectMenuList(SecurityUtils.getLoginUser());
        AjaxResult ajax = AjaxResult.success();
        ajax.put("checkedKeys", comMenuService.selectMenuListByRoleId(roleId));
        ajax.put("menus", comMenuService.buildMenuTreeSelect(menus));
        return ajax;
    }
}
